import { selectedUserRowsType, UserManageType } from "@/configs/types";
import {
  Button,
  message,
  Popconfirm,
  PopconfirmProps,
  Select,
  Space,
  TableProps,
} from "antd";
import { useEffect, useState } from "react";
import style from "./index.module.scss";
import TableCom from "../TableCom";
import Search, { SearchProps } from "antd/es/input/Search";
import { delUser, getUser, updateUserStatus } from "@/api";
import React from "react";
export default function UserManage() {
  //用户管理表头
  const userManageColumns = [
    {
      title: "用户名",
      dataIndex: "userAccount",
      key: "userAccount",
      align: "center",
    },
    // {
    //   title: "性别",
    //   dataIndex: "userSex",
    //   key: "userSex",
    //   align: "center",
    // },
    {
      title: "出生日期",
      dataIndex: "userBirth",
      key: "userBirth",
      align: "center",
    },
    {
      title: "地址",
      dataIndex: "userAddress",
      key: "userAddress",
      align: "center",
    },
    {
      title: "个人签名",
      dataIndex: "userIntroduce",
      key: "userIntroduce",
      align: "center",
      ellipsis: true,
    },
    {
      title: "状态",
      dataIndex: "userStatus",
      key: "userStatus",
      align: "center",
      width: "120px",
      render: (_: any, record: any) => {
        return (
          <Select
            value={record.userStatus}
            style={{ width: 100 }}
            onChange={() => handleStatusChange(record.id)}
            options={[
              { value: "1", label: "禁用" },
              { value: "0", label: "启用" },
            ]}
          />
        );
      },
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
      align: "center",
      ellipsis: true,
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      align: "center",
      render: (_: any, record: any) => (
        <Space size="middle">
          <Popconfirm
            title="删除这条数据"
            description="你确定要删除这条数据吗"
            onConfirm={() => deleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const [users, setUsers] = useState([]);
  const [pageOptions, setPageOptions] = useState({ current: 1, pageSize: 10 });
  const [selectedRowsData, setSelectedRowsData] =
    useState<selectedUserRowsType>({
      selectedRowKeys: [],
      selectedRows: [],
    });
  const handlePageChange = (current: number, pageSize: number) => {
    console.log(current, pageSize);
    setPageOptions({ current, pageSize });
  };
  const paginationOptions = {
    current: pageOptions.current,
    pageSize: pageOptions.pageSize,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条`,
    onChange: handlePageChange,
  };

  const getUsers = async (pageNum: number, pageSize: number) => {
    const res = await getUser({
      pageNum,
      pageSize,
    });
    const data = res.data.data.records.filter(
      (item: any) => item.userAccount !== "admin"
    );
    setUsers(data);
  };

  const deleteUser = async (id: number) => {
    const res = await delUser([id]);
    getUsers(pageOptions.current, pageOptions.pageSize);
    res.data.code === 200
      ? message.success(res.data.msg)
      : message.error(res.data.msg);
  };
  useEffect(() => {
    getUsers(1, 10);
  }, []);

  const rowSelection: TableProps<UserManageType>["rowSelection"] = {
    onChange: (
      selectedRowKeys: React.Key[],
      selectedRows: UserManageType[]
    ) => {
      setSelectedRowsData({ selectedRowKeys, selectedRows });
    },
    getCheckboxProps: (record) => ({
      disabled: record.userName === "Disabled User", // Column configuration not to be checked
      name: record.userName,
    }),
    selectedRowKeys: selectedRowsData.selectedRowKeys,
  };
  //  根据用户名查询
  const onUserNameSearch: SearchProps["onSearch"] = async (value, _e, info) => {
    const res = await getUser({ userName: value });
    console.log(res);

    setUsers(res.data.data.records);
  };
  //根据状态查询
  const handleSearchByStatus = async (value: number) => {
    const res = await getUser({ userStatus: value });
    setUsers(res.data.data.records);
  };
  //直接修改状态
  const handleStatusChange = async (id: number) => {
    const res = await updateUserStatus([id]);
    if (res.data.code === 200) {
      getUsers(pageOptions.current, pageOptions.pageSize);
      message.success(res.data.msg);
    } else message.error(res.data.msg);
  };

  //批量修改状态
  const onBulkOperations = async (type: string) => {
    let res;
    if (type === "update") {
      res = await updateUserStatus(selectedRowsData.selectedRowKeys);
    } else if (type === "delete") {
      res = await delUser(selectedRowsData.selectedRowKeys);
    }
    if (res!.data.code === 200) {
      getUsers(pageOptions.current, pageOptions.pageSize);
      setSelectedRowsData({ selectedRowKeys: [], selectedRows: [] });
      message.success(res!.data.msg);
    } else message.error(res!.data.msg);
  };

  return (
    <div className={style["Container"]}>
      <div className={style["header"]}>
        <Space>
          <Search
            placeholder="用户名搜索"
            onSearch={onUserNameSearch}
            style={{ width: 200 }}
            maxLength={32}
          />
          <Button onClick={() => onBulkOperations("delete")}>批量删除</Button>
          <Button onClick={() => onBulkOperations("update")}>
            批量修改状态
          </Button>
        </Space>

        <Select
          placeholder="状态查询"
          style={{ width: 120 }}
          onChange={handleSearchByStatus}
          options={[
            { value: "1", label: "禁用" },
            { value: "0", label: "启用" },
          ]}
        />
      </div>
      <div className={style["content"]}>
        <TableCom
          paginationOptions={paginationOptions}
          dataSource={users}
          columns={userManageColumns}
          rowSelection={rowSelection}
        />
      </div>
    </div>
  );
}
